package top.hidoctor.auscultation.feature.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tang.net.NetClient;
import com.tang.user.UserInfoManager;
import com.tang.util.AppUtil;
import com.tang.util.BigDecimalUtil;
import com.tang.util.DensityUtil;
import com.tang.util.GsonUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import top.hidoctor.auscultation.App;
import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.adapter.ChooseAdapter;
import top.hidoctor.auscultation.adapter.ScaleAdapter;
import top.hidoctor.auscultation.adapter.SekaAdapter;
import top.hidoctor.auscultation.base.BaseActivity;
import top.hidoctor.auscultation.base.Constant;
import top.hidoctor.auscultation.bean.ChooseInfo;
import top.hidoctor.auscultation.bean.CoordinateBean;
import top.hidoctor.auscultation.bean.LableBean;
import top.hidoctor.auscultation.bean.MarkDetailBean;
import top.hidoctor.auscultation.bean.ProblemBean;
import top.hidoctor.auscultation.bean.RectBean;
import top.hidoctor.auscultation.bean.SPBean;
import top.hidoctor.auscultation.bean.SampleDetailBean;
import top.hidoctor.auscultation.event.WorkYbEvent;
import top.hidoctor.auscultation.net.c.WorkbenchContract;
import top.hidoctor.auscultation.net.p.WorkbenchPresenter;
import top.hidoctor.auscultation.net.req.DictionaryReq;
import top.hidoctor.auscultation.net.req.MarkReq;
import top.hidoctor.auscultation.utils.LabelUtils;
import top.hidoctor.auscultation.view.MyRectView;
import top.hidoctor.auscultation.view.SPlineView;
import top.hidoctor.auscultation.view.ChooseDocPop;
import top.hidoctor.auscultation.widget.Player2;
import top.hidoctor.auscultation.widget.listener.OnLongClickListener;
import top.hidoctor.auscultation.widget.listener.OnRectClickListener;
import top.hidoctor.auscultation.widget.mark.ImageMark;
import top.hidoctor.auscultation.widget.mark.Mark;
import top.hidoctor.auscultation.widget.mark.SelectBean;
import top.hidoctor.auscultation.widget.mark.bean.MarkBean;
import top.hidoctor.auscultation.widget.tree.AndroidTreeView;
import top.hidoctor.auscultation.widget.tree.NodeIDFormat;
import top.hidoctor.auscultation.widget.tree.TreeNode;
import top.hidoctor.auscultation.widget.tree.TypeBeanString;

import static com.tang.util.BigDecimalUtil.div;
import static com.tang.util.BigDecimalUtil.mul;

public class LabelDetailActivity extends BaseActivity implements View.OnClickListener, WorkbenchContract.View {
    private ImageButton ibBack, ibBofang;
    private TextView tvName, tvBeishu, tvYinliang, tvX, tvColor, tvPingfen, tvZhengduan, tvKuangxuan, tvAllLong, tvLong, tvY, tvBiaozhuType, tvBufu, tvYinan;
    private Button btnChooseDoc, btnWancheng, btnTingzhenmoshi, btnQiehuan, btnBiaozhuSave, btnChakanbaogao;
    private LinearLayout llSection, llBiaozhuWancheng, llSp, llRemark, llBiaozhu, llContent;
    private RelativeLayout treeLayout, rlSpLeft;
    private EditText editRemark;
    private CheckBox checkbox1, checkbox2;
    private ChooseDocPop chooseDocPop;
    private ImageView ivContent;
    private RecyclerView rcScale, rcSeka;
    private List<ChooseInfo> tingzhenList = new ArrayList<>();
    private List<ChooseInfo> bofangList = new ArrayList<>();
    private List<ChooseInfo> yinliangList = new ArrayList<>();
    private List<ChooseInfo> xZhouList = new ArrayList<>();
    private List<ChooseInfo> yZhouList = new ArrayList<>();
    private AlertDialog pingfenDialog;
    private DrawerLayout drawer;
    private AlertDialog wanchengDialog;
    private AlertDialog chooseDialog;
    private ChooseAdapter chooseAdapter;
    private ImageMark imageMark;
    protected int currentColor = 0xFFd0021b;
    private WorkbenchPresenter presenter;
    private LableBean.SampleBean info;
    private String sampleId;//样本id
    private String labelId;//标注包id
    private SeekBar seekBar;
    private Player2 player;
    private int playStatus = 0;// 0 零状态  1 开始 2 暂停
    private HorizontalScrollView horizontal;
    List<int[]> sectionList = new ArrayList<>();//存放听诊区

    private double beisu = 1;//倍速1
    private int yinliang = 1;//音量1
    private int xMultiple = 5;//x轴5
    private int yMultiple = 10;//y轴10
    private int widths;//总长度
    private MarkDetailBean markDetailBean;
    private boolean spMode = false;//1:tp  2:sp
    private SPBean spBean;
    private AndroidTreeView mTreeView;
    private Integer labelStatus;
    private static List<TypeBeanString> labelList = new ArrayList<>();
    private static List<TypeBeanString> finishList = new ArrayList<>();
    private AlertDialog biaozhuDialog;
    private List<CoordinateBean> list;
    private MyRectView view;
    private NestedScrollView drawerScroll;
    private FrameLayout frameRect;
    private CoordinateBean currentInfo;
    private MarkReq markReq;
    private int drawType; // 1 框选  2 整段  3 完成


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.act_label_detail);
        initNet();
        initView();
        initEvent();
    }

    /**
     *
     */
    private void initNet() {
        presenter = new WorkbenchPresenter(this, this);
        info = (LableBean.SampleBean) getIntent().getSerializableExtra("info");

        sampleId = getIntent().getStringExtra("sampleId");
        labelId = getIntent().getStringExtra("labelId");
        //获取 标注详情
        presenter.getMarkDetail(labelId, sampleId);
        //获取SP点数据
        presenter.downloadFile(info.getSampleDetail().getWavDataPath());
        //获取整段标注 完成标注问题字典
        //框选标注 整段标注
        DictionaryReq req = new DictionaryReq();
        req.setGroupCode("SAMPLE_MARK_OPTION");
        presenter.getDictionaryList1(req);
        // 完成标注
        req.setGroupCode("SAMPLE_MARK_RESULT");
        presenter.getDictionaryList2(req);

        //更新标注包req
        markReq = new MarkReq();
    }

    private void initEvent() {
        llBiaozhu.setVisibility(View.VISIBLE);
        //初始化页面数据
        if (info != null) {
            tvName.setText(UserInfoManager.getInstance().getUserInfo().getRealName());
            //设置图片
            xZhouList.get(4).setCheck(true);
            widths = (int) (Constant.width * Math.pow(2, xMultiple));
            upxAxis();
            //设置bofang数据
            seekBar.setMax(info.getSampleDetail().getDuration());
            tvAllLong.setText(AppUtil.stringForTime2(info.getSampleDetail().getDuration()));

            //标注状态：0：未开始；10：标注开始；20：标注完成 30 超时
            labelStatus = info.getLabelStatus();
//            labelStatus = 10;
            if (labelStatus == 20 || labelStatus == 30) {// 标注结束
                tvKuangxuan.setVisibility(View.GONE);
            } else {
                tvKuangxuan.setVisibility(View.VISIBLE);
            }
        }
    }

    @SuppressLint("NewApi")
    private void initView() {
        ibBofang = findViewById(R.id.ib_bofang);
        llContent = findViewById(R.id.ll_content);
        ibBack = findViewById(R.id.ib_back);
        tvName = findViewById(R.id.tv_name);
        btnChooseDoc = findViewById(R.id.btn_choose_doc);
        tvBeishu = findViewById(R.id.tv_beishu);
        tvYinliang = findViewById(R.id.tv_yinliang);
        tvX = findViewById(R.id.tv_x);
        ivContent = findViewById(R.id.iv_content);
        rcScale = findViewById(R.id.rc_scale);
        rcSeka = findViewById(R.id.rc_seka);
        tvPingfen = findViewById(R.id.tv_pingfen);
        tvZhengduan = findViewById(R.id.tv_zhengduan);
        btnWancheng = findViewById(R.id.btn_wancheng);
        btnTingzhenmoshi = findViewById(R.id.btn_tingzhenmoshi);
        llBiaozhu = findViewById(R.id.ll_biaozhu);
        seekBar = findViewById(R.id.seekBar);
        tvAllLong = findViewById(R.id.tv_all_long);
        tvLong = findViewById(R.id.tv_long);
        horizontal = findViewById(R.id.horizontal);
        llSection = findViewById(R.id.ll_section);
        btnQiehuan = findViewById(R.id.btn_qiehuan);
        rlSpLeft = findViewById(R.id.rl_sp_left);
        llSp = findViewById(R.id.ll_sp);
        tvY = findViewById(R.id.tv_y);
        drawerScroll = findViewById(R.id.drawer_scroll);
        frameRect = findViewById(R.id.frame_rect);
        btnChakanbaogao = findViewById(R.id.btn_chakanbaogao);
        initDrawer();

        ibBack.setOnClickListener(this);
        ibBofang.setOnClickListener(this);
        btnChooseDoc.setOnClickListener(this);
        tvBeishu.setOnClickListener(this);
        tvPingfen.setOnClickListener(this);
        tvZhengduan.setOnClickListener(this);
        btnWancheng.setOnClickListener(this);
        btnTingzhenmoshi.setOnClickListener(this);
        btnChakanbaogao.setOnClickListener(this);
        tvYinliang.setOnClickListener(this);
        tvX.setOnClickListener(this);
        tvY.setOnClickListener(this);
        btnQiehuan.setOnClickListener(this);

        rcScale.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        rcScale.setAdapter(new ScaleAdapter(R.layout.item_scale, Arrays.asList(Constant.scales)));

        rcSeka.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        rcSeka.setAdapter(new SekaAdapter(R.layout.item_seka, Arrays.asList(Constant.sekas)));

        for (int i = 0; i < Constant.tingzhen.length; i++) {
            tingzhenList.add(new ChooseInfo(Constant.tingzhen[i], false));
        }
        //默认1倍
        tvBeishu.setText("1X");
        beisu = 1;
        for (int i = 0; i < Constant.bofang.length; i++) {
            bofangList.add(new ChooseInfo(Constant.bofang[i] + "X", i == 2 ? true : false));
        }
        //默认1倍
        tvYinliang.setText("1X");
        yinliang = 1;
        for (int i = 0; i < Constant.yinliang.length; i++) {
            yinliangList.add(new ChooseInfo(Constant.yinliang[i] + "X", i == 0 ? true : false));
        }
        //默认1倍
        tvX.setText("5X");
        xMultiple = 5;
        for (int i = 0; i < Constant.xzhou.length; i++) {
            xZhouList.add(new ChooseInfo(Constant.xzhou[i] + "X", i == Constant.xzhou.length - 1 ? true : false));
        }
        //默认10倍
        yMultiple = 10;
        tvY.setText("10X");
        for (int i = 0; i < Constant.yzhou.length; i++) {
            yZhouList.add(new ChooseInfo(Constant.yzhou[i] + "X", i == Constant.yzhou.length - 1 ? true : false));
        }


//        标注
        imageMark = findViewById(R.id.imagemark);
        tvKuangxuan = findViewById(R.id.tv_kuangxuan);
        imageMark.setImageview(ivContent);
        tvKuangxuan.setOnClickListener(this);

        imageMark.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public void onClick(Mark mark) {
                RectF realBounds = mark.getRealBounds();

                Log.e("TAG", "onClick:width " + ivContent.getWidth());
                Log.e("TAG", "onClick:hight " + ivContent.getHeight());
                Log.e("TAG", "onClick:left " + realBounds.left);
                Log.e("TAG", "onClick:top " + realBounds.top);
                Log.e("TAG", "onClick:right " + realBounds.right);
                Log.e("TAG", "onClick:bottom " + realBounds.bottom);
                handler.sendEmptyMessage(1);
            }
        });

        imageMark.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

            }
        });
        imageMark.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                List<Mark> shapeMarks = imageMark.getShapeMarks();
                if (shapeMarks.size() > 0) {
                    tvKuangxuan.setText("确认标注");
                }
                return false;
            }
        });


        player = new Player2(seekBar);
        player.setOnplayerListener(new Player2.OnplayerListener() {
            @Override
            public void onCompletion() {
                //播放完成
                playStatus = 0;
                ibBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_zanting));
                tvLong.setText("/00:00");
            }
        });

        horizontal.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//                Log.e("TAG", "onScrollChange: scrollX " + scrollX + " oldScrollX " + oldScrollX + " scrollY " + scrollY);
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                final int currentPosition = seekBar.getProgress();
                tvLong.setText("/" + AppUtil.stringForTime2(currentPosition));
                Log.e("TAG", " onProgressChanged:  " + seekBar.getProgress());
                Integer duration = info.getSampleDetail().getDuration();
//                真实滑动长度
                int width = 0;
                if (horizontal.getWidth() < widths) {
                    width = widths - horizontal.getWidth();
                } else {
                    width = horizontal.getWidth();
                }
                horizontal.smoothScrollTo((int) Math.round(BigDecimalUtil.div(currentPosition, duration) * width), 0);
                Log.e("TAG", horizontal.getWidth() + " smoothScrollTo: " + Math.round(BigDecimalUtil.div(currentPosition, duration) * widths));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                player.seekTo(seekBar.getProgress());
            }
        });
    }

    /**
     *
     */
    //抽屉布局部分
    private void initDrawer() {
        drawer = findViewById(R.id.drawer);
        btnBiaozhuSave = findViewById(R.id.btn_biaozhu_save);
        tvBiaozhuType = findViewById(R.id.tv_biaozhu_type);
        treeLayout = findViewById(R.id.layout_tree_view);
        llBiaozhuWancheng = findViewById(R.id.ll_biaozhu_wancheng);
        llRemark = findViewById(R.id.ll_remark);
        editRemark = findViewById(R.id.edit_remark);
        tvBufu = findViewById(R.id.tv_bufu);
        tvYinan = findViewById(R.id.tv_yinan);
        checkbox1 = findViewById(R.id.checkbox1);
        checkbox2 = findViewById(R.id.checkbox2);
        btnBiaozhuSave.setOnClickListener(this);
        tvYinan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkbox1.setChecked(!checkbox1.isChecked());
            }
        });
        tvBufu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkbox2.setChecked(!checkbox2.isChecked());
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_back:
                onBackPressed();
                break;
            case R.id.ib_bofang:
                if (!AppUtil.isFastClick()) {
                    if (TextUtils.isEmpty(info.getSampleDetail().getWavDataPath())) {
                        showToast("文件获取异常");
                        return;
                    }
                    if (playStatus == 0) { // 播放状态
                        playStatus = 1;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                player.playUrl(NetClient.IMG_URL + info.getSampleDetail().getWavPath());

                            }
                        }).start();
                        ibBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_bofang));
                    } else if (playStatus == 1) {// 暂停状态
                        playStatus = 2;
                        if (player != null) {
                            player.pause();
                        }
                        ibBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_zanting));
                    } else if (playStatus == 2) { //继续播放
                        playStatus = 1;
                        if (player != null) {
                            player.play();
                        }
                        ibBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_bofang));
                    }
                }
                break;
            case R.id.btn_choose_doc:
                if (!AppUtil.isFastClick()) {
                    chooseDocPop = new ChooseDocPop(this, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                        }
                    });
                    chooseDocPop.showAsDropDown(btnChooseDoc);
                }
                break;
            case R.id.tv_beishu:
                if (!AppUtil.isFastClick()) {
                    showChoose(2);
                }
                break;
            case R.id.tv_pingfen:
                if (!AppUtil.isFastClick()) {
                    showPingFen();
                }
                break;
            case R.id.tv_kuangxuan:
                if (!AppUtil.isFastClick()) {
                    List<Mark> shapeMarks = imageMark.getShapeMarks();
                    if (shapeMarks.size() == 0) {
                        SelectBean select = new SelectBean(Mark.Shape.RECT);
                        select.setColor(currentColor);
                        imageMark.addMark(select.getMark());
                        showToast("请开始标注");
                    } else if (shapeMarks.get(0) != null && shapeMarks.get(0).getRealBounds() == null) {
                        SelectBean select = new SelectBean(Mark.Shape.RECT);
                        select.setColor(currentColor);
                        imageMark.addMark(select.getMark());
                        showToast("请开始标注");
                    } else {
                        editRemark.setText("");
                        drawType = 1;
                        editRemark.setEnabled(true);
                        btnBiaozhuSave.setVisibility(View.VISIBLE);
                        llBiaozhuWancheng.setVisibility(View.GONE);
                        llRemark.setVisibility(View.VISIBLE);
                        tvBiaozhuType.setText("框选标注");
                        initTreeView("SAMPLE_MARK_OPTION", null);
                        drawer.openDrawer(Gravity.RIGHT);
                    }
                }
                break;
            case R.id.tv_zhengduan:
                //如果是超时 完成状态 禁止点击
                if (!AppUtil.isFastClick()) {
                    drawType = 2;
                    editRemark.setText("");
                    btnBiaozhuSave.setText("保存");
                    if (labelStatus == 20 || labelStatus == 30) {
                        editRemark.setEnabled(false);
                        btnBiaozhuSave.setVisibility(View.GONE);
                    }
                    editRemark.setText((markDetailBean != null && markDetailBean.getMarkRemark() != null) ? markDetailBean.getMarkRemark() : "");
                    llBiaozhuWancheng.setVisibility(View.GONE);
                    llRemark.setVisibility(View.VISIBLE);
                    tvBiaozhuType.setText("整段标注");

                    initTreeView("SAMPLE_MARK_OPTION", null);
                    drawer.openDrawer(Gravity.RIGHT);

                }
                break;
            case R.id.btn_wancheng:
                if (!AppUtil.isFastClick()) {
                    drawType = 3;

                    //如果是超时 完成状态 禁止点击
                    btnBiaozhuSave.setText("完成标注");
                    if (labelStatus == 20 || labelStatus == 30) {
                        tvYinan.setEnabled(false);
                        tvBufu.setEnabled(false);
                        checkbox1.setEnabled(false);
                        checkbox2.setEnabled(false);
                        btnBiaozhuSave.setVisibility(View.GONE);

                    }
                    checkbox1.setChecked(markDetailBean.getIsDifficult() == 1 ? true : false);
                    checkbox2.setChecked(markDetailBean.getIsSame() == 1 ? true : false);
                    // 完成标注
                    llRemark.setVisibility(View.GONE);
                    llBiaozhuWancheng.setVisibility(View.VISIBLE);
                    tvBiaozhuType.setText("标注完成");
                    initTreeView("SAMPLE_MARK_RESULT", null);
                    drawer.openDrawer(Gravity.RIGHT);

//                showWancheng();
                }
                break;
            case R.id.btn_biaozhu_save:
                if (!AppUtil.isFastClick()) {
                    if (mTreeView != null) {
                        // 在多选状态时，通过 getSelected 可以获取当前所选的叶子节点的集合
                        List<TreeNode> selected = mTreeView.getSelected();

                        List<String> markOption = new ArrayList<>();
                        for (TreeNode node : selected) {
                            markOption.add(node.getId());
                        }

                        if (markOption.size() == 0) {
                            showToast("请选择");
                            return;
                        }
                        if (markDetailBean == null) {
                            showToast("操作失败，样本详情获取异常！");
                            return;
                        }
                        if (drawType == 1) {
                            int comparisonWidth = (int) (Constant.width * Math.pow(2, xMultiple));// 当前宽度
                            RectF realBouds = imageMark.getRealBouds();
                            //根据比例获取 top  height
                            Float x1 = realBouds.left - 6;
                            Double top = div(realBouds.top, ivContent.getHeight());
                            Float x2 = realBouds.right - 6;
                            Double height = div((realBouds.bottom - realBouds.top), ivContent.getHeight());
                            List<Double> duration = new ArrayList<>();
                            duration.add(BigDecimalUtil.mul(BigDecimalUtil.div(x1, comparisonWidth), info.getSampleDetail().getDuration()));
                            duration.add(BigDecimalUtil.mul(BigDecimalUtil.div(x2, comparisonWidth), info.getSampleDetail().getDuration()));

                            currentInfo = new CoordinateBean();
                            currentInfo.setHeight(height);
                            currentInfo.setTop(top);
                            currentInfo.setZoom(xMultiple);
                            currentInfo.setDuration(duration);
                            currentInfo.setMarkOption(markOption);
                            currentInfo.setRemark(editRemark.getText().toString());
                            currentInfo.setId(System.currentTimeMillis() + "");
                            final String coordinate = markDetailBean.getCoordinate();
                            List<CoordinateBean> coorlist = new ArrayList<>();
                            if (!TextUtils.isEmpty(coordinate)) {
                                List<CoordinateBean> list = GsonUtil.parseJson(coordinate, new TypeToken<List<CoordinateBean>>() {
                                });
                                coorlist.addAll(list);
                            }
                            coorlist.add(currentInfo);

                            markReq.setId(markDetailBean.getId());
                            markReq.setCoordinate(GsonUtil.toJsonStr(coorlist));

                            presenter.updataMark(labelId, sampleId, markDetailBean.getId(), markReq);
                        } else if (drawType == 2) {
                            markReq.setId(markDetailBean.getId());
                            markReq.setCoordinate(markDetailBean.getCoordinate());
                            markReq.setMarkRemark(editRemark.getText().toString());
                            markReq.setMarkOption(markOption.toString().substring(1, markOption.toString().length() - 1).replace(" ", ""));
                            presenter.updataMark(labelId, sampleId, markDetailBean.getId(), markReq);
                        } else if (drawType == 3) {
                            markReq.setId(markDetailBean.getId());
                            markReq.setCoordinate(markDetailBean.getCoordinate());
                            markReq.setMarkRemark(markDetailBean.getMarkRemark());
                            markReq.setMarkOption(markDetailBean.getMarkOption());
                            markReq.setDiagnosis(markOption.toString().substring(1, markOption.toString().length() - 1).replace(" ", ""));
                            markReq.setIsDifficult(checkbox1.isChecked() ? 1 : 0);
                            markReq.setIsSame(checkbox2.isChecked() ? 1 : 0);
                            //进行 结束标注

                            presenter.updataMarks(labelId, sampleId, UserInfoManager.getInstance().getUserInfo().getUserId());
                        }

//                        presenter.updataMark(labelId, sampleId, markDetailBean.getId(), markReq);
                    }
                }
                break;
            case R.id.btn_tingzhenmoshi:
                if (!AppUtil.isFastClick()) {
                    showChoose(1);
                }
                break;
            case R.id.tv_yinliang:
                if (!AppUtil.isFastClick()) {
                    showChoose(3);
                }
                break;
            case R.id.tv_x:
                if (!AppUtil.isFastClick()) {
                    showChoose(4);
                }
                break;
            case R.id.tv_y:
                if (!AppUtil.isFastClick()) {
                    showChoose(5);
                }
                break;
            case R.id.btn_qiehuan:
//                if (!AppUtil.isFastClick()) {
                spMode = !spMode;
                if (spMode) {
                    btnQiehuan.setText("切换至PH");
                    rlSpLeft.setVisibility(View.VISIBLE);
                    rcScale.setVisibility(View.GONE);
                    rcSeka.setVisibility(View.GONE);
                    imageMark.setVisibility(View.GONE);
                    llSp.setVisibility(View.VISIBLE);
                    tvY.setVisibility(View.VISIBLE);
                    tvKuangxuan.setVisibility(View.GONE);
                } else {
                    btnQiehuan.setText("切换至SP");
                    rlSpLeft.setVisibility(View.GONE);
                    rcScale.setVisibility(View.VISIBLE);
                    rcSeka.setVisibility(View.VISIBLE);
                    imageMark.setVisibility(View.VISIBLE);
                    llSp.setVisibility(View.GONE);
                    tvY.setVisibility(View.GONE);
                    if (labelStatus != 20 && labelStatus != 30) {
                        tvKuangxuan.setVisibility(View.VISIBLE);
                    }
                }
//                }
                break;
            case R.id.btn_chakanbaogao:
                if (!AppUtil.isFastClick()) {
                    Intent intent = new Intent(LabelDetailActivity.this, H5Activity.class);
                    intent.putExtra("url", "https://www.baidu.com");
                    intent.putExtra("title", "查看报告");
                    startActivity(intent);
                }
                break;
        }
    }


    /**
     * 动态显示侧边栏 问题内容
     */
    private void initTreeView(String type, CoordinateBean coordinateBean) {
        if (type.equals("SAMPLE_MARK_RESULT") && finishList.size() == 0) {
            return;
        }
        if (type.equals("SAMPLE_MARK_OPTION") && labelList.size() == 0) {
            return;
        }
        //滑到顶部
        drawerScroll.scrollTo(0, 0);
        treeLayout.removeAllViews();
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mTreeView = new AndroidTreeView(this);
        mTreeView.setLayoutParams(params);
        mTreeView.setMultiSelEnable(true);
        mTreeView.setNodeIdFormat(NodeIDFormat.STRING);
        mTreeView.setNestedScrollingEnabled(false);
        mTreeView.setTitleTextColor("#000000");
        mTreeView.setTitleTextSize(12);
        mTreeView.setLevelPadding(20);   // 设置层级缩进大小，可选

        // 绑定数据，必须在最后一步调用，否则上述自定义数据将无效
//        labelStatus 20 30  标注结束
        if (labelStatus == 20 || labelStatus == 30 || coordinateBean != null) {
            if (type.equals("SAMPLE_MARK_RESULT")) {
                mTreeView.bindData(finishList, markDetailBean.getDiagnosis(), false);
            } else if (type.equals("SAMPLE_MARK_OPTION")) {
                if (coordinateBean != null) {
                    mTreeView.bindData(labelList, !TextUtils.isEmpty(coordinateBean.getMarkOption().toString()) ? coordinateBean.getMarkOption().toString() : "", false);
                } else {
                    mTreeView.bindData(labelList, (markDetailBean != null && !TextUtils.isEmpty(markDetailBean.getMarkOption())) ? markDetailBean.getMarkOption() : "", false);
                }
            }
        } else {
            if (drawType == 2) {
                mTreeView.bindData(labelList, (markDetailBean != null && !TextUtils.isEmpty(markDetailBean.getMarkOption())) ? markDetailBean.getMarkOption() : "", true);
            } else if (drawType == 3) {
                mTreeView.bindData(finishList, (markDetailBean != null && !TextUtils.isEmpty(markDetailBean.getDiagnosis())) ? markDetailBean.getDiagnosis() : "", true);
            } else {
                mTreeView.bindData(type.equals("SAMPLE_MARK_RESULT") ? finishList : type.equals("SAMPLE_MARK_OPTION") ? labelList : null, "", true);
            }
        }
        // 将 TreeView 添加到 FrameLayout 中显示
        treeLayout.addView(mTreeView);
    }

    /**
     * 选择框
     *
     * @param type
     */
    private void showChoose(final int type) {

        //1 听诊模式    2 倍速  3 音量  4 X轴
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_choose, null);
        builder.setView(dialogView);
        chooseDialog = builder.create();
        chooseDialog.setCanceledOnTouchOutside(true);
        chooseDialog.show();

        chooseDialog.getWindow().setLayout(DensityUtil.dip2px(this, 220), LinearLayout.LayoutParams.WRAP_CONTENT);

        RecyclerView rc = dialogView.findViewById(R.id.rc);
        TextView tvTitle = dialogView.findViewById(R.id.tv_title);
        rc.setLayoutManager(new LinearLayoutManager(this));
        rc.setAdapter(chooseAdapter = new ChooseAdapter(R.layout.item_choose, null));
        chooseAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (type == 1) {
                    for (int i = 0; i < tingzhenList.size(); i++) {
                        tingzhenList.get(i).setCheck(false);
                    }
                    tingzhenList.get(position).setCheck(true);
                    btnTingzhenmoshi.setText(tingzhenList.get(position).getName());
                } else if (type == 2) {//播放速度
                    for (int i = 0; i < bofangList.size(); i++) {
                        bofangList.get(i).setCheck(false);
                    }
                    beisu = Constant.bofang[position];
                    bofangList.get(position).setCheck(true);
                    tvBeishu.setText(bofangList.get(position).getName());

                    if (player != null) {
                        player.setBeisu(beisu);
                    }

                } else if (type == 3) {//声音
                    for (int i = 0; i < yinliangList.size(); i++) {
                        yinliangList.get(i).setCheck(false);
                    }
                    yinliangList.get(position).setCheck(true);
                    tvYinliang.setText(yinliangList.get(position).getName());
                    yinliang = Constant.yinliang[position];
                } else if (type == 4) { // x轴放大
                    for (int i = 0; i < xZhouList.size(); i++) {
                        xZhouList.get(i).setCheck(false);
                    }
                    xMultiple = position + 1;
                    // 总长度
                    widths = (int) (Constant.width * Math.pow(2, xMultiple));
                    xZhouList.get(position).setCheck(true);
                    tvX.setText(xZhouList.get(position).getName());
                    upxAxis();
                    if (spMode) {
                        drawSpView();
                    }

                    //重绘 矩形框
                    getRect(list);

                } else if (type == 5) {// y轴放大
                    for (int i = 0; i < yZhouList.size(); i++) {
                        yZhouList.get(i).setCheck(false);
                    }
                    yMultiple = Constant.yzhou[position];
                    tvY.setText(yZhouList.get(position).getName());
                    yZhouList.get(position).setCheck(true);
                    drawSpView();
                }
                //重置 滚动
                horizontal.smoothScrollTo(0, 0);
                seekBar.setProgress(0);
                if (player != null && type != 3) {
                    player.pause();
                    playStatus = 0;
                    ibBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_zanting));
                } else {
                    player.pause();
                    playStatus = 1;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            player.playUrl(NetClient.BASE_URL + "file/1?path=" + info.getSampleDetail().getWavPath() + "&type=" + yinliang);

                        }
                    }).start();
                    ibBofang.setImageDrawable(getResources().getDrawable(R.mipmap.ic_bofang));
                }
                chooseAdapter.notifyDataSetChanged();
                chooseDialog.dismiss();
            }
        });


        if (type == 1) {
            chooseAdapter.setNewData(tingzhenList);
            tvTitle.setText("请选择：听诊模式");
        } else if (type == 2) {
            chooseAdapter.setNewData(bofangList);
            tvTitle.setText("请选择：播放倍速");
        } else if (type == 3) {
            chooseAdapter.setNewData(yinliangList);
            tvTitle.setText("请选择：音量");
        } else if (type == 4) {
            chooseAdapter.setNewData(xZhouList);
            tvTitle.setText("请选择：X轴放大");
        } else if (type == 5) {
            chooseAdapter.setNewData(yZhouList);
            tvTitle.setText("请选择：y轴放大");
        }
    }

    /**
     * X轴放大
     *
     * @param
     */
    private void upxAxis() {
        //重新设置 horizontal 的长度
        drawSection();
        Glide.with(LabelDetailActivity.this)
                .asBitmap()
                .load(NetClient.IMG_URL + info.getSampleDetail().getWavPowerPics())
                .into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        ivContent.setScaleType(ImageView.ScaleType.FIT_XY);
                        ViewGroup.LayoutParams params = ivContent.getLayoutParams();
                        final int heights = llContent.getHeight() - DensityUtil.dip2px(mContext, 20);
                        params.width = widths;
                        params.height = heights;
                        ivContent.setLayoutParams(params);
                        ivContent.setImageBitmap(resource);
                    }
                });
    }


    private void showPingFen() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_pingfen, null);
        builder.setView(dialogView);
        pingfenDialog = builder.create();
        pingfenDialog.setCanceledOnTouchOutside(true);
        pingfenDialog.show();

        RatingBar ratingbar = dialogView.findViewById(R.id.ratingbar);
        TextView tvCancel = dialogView.findViewById(R.id.tv_cancel);
        TextView tvConfirm = dialogView.findViewById(R.id.tv_confirm);
        final TextView tvPingfen = dialogView.findViewById(R.id.tv_pingfen);
        ratingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
                tvPingfen.setText("优秀：" + (int) Math.floor(v) + "分");
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pingfenDialog.dismiss();
            }
        });

    }

    //数据的接收
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    showBiaozhu(null);
                    break;
            }
        }
    };


    @Override
    public void getMarkDetailSuc(MarkDetailBean bean) {
        markDetailBean = bean;
        //分区
        //500 12862
        sectionList.clear();
        int[] first = LabelUtils.getSectionStartAndEnd(bean.getAreaFirst());
        int[] second = LabelUtils.getSectionStartAndEnd(bean.getAreaSecond());
        int[] third = LabelUtils.getSectionStartAndEnd(bean.getAreaThird());
        int[] fourth = LabelUtils.getSectionStartAndEnd(bean.getAreaFourth());
        int[] fifth = LabelUtils.getSectionStartAndEnd(bean.getAreaFifth());
        sectionList.add(first);
        sectionList.add(second);
        sectionList.add(third);
        sectionList.add(fourth);
        sectionList.add(fifth);
        drawSection();// 默认五倍

        //绘制 标注框
        final String coordinate = bean.getCoordinate();
        Log.i("TAG", "getMarkDetailSuc: " + coordinate);
        if (!TextUtils.isEmpty(coordinate)) {
            list = GsonUtil.parseJson(coordinate, new TypeToken<List<CoordinateBean>>() {
            });
            getRect(list);
        }
    }

    private void getRect(final List<CoordinateBean> list) {
        if (list == null || list.size() == 0) {
            frameRect.removeAllViews();
            return;
        }
        frameRect.removeAllViews();
//        int width = (int) (Constant.width * Math.pow(2, 5));//最大长度
        int currentWidth = (int) (Constant.width * Math.pow(2, xMultiple));// 当前长度

        for (int i = 0; i < list.size(); i++) {
//            int zoom = list.get(i).getZoom();
            int comparisonWidth = (int) (Constant.width * Math.pow(2, 5));// 对比长度
            Float x = Float.valueOf(mul(currentWidth, div(list.get(i).getDuration().get(0), info.getSampleDetail().getDuration())) + "");
            Float y = Float.valueOf(BigDecimalUtil.mul(ivContent.getHeight(), list.get(i).getTop()) + "");
            Float w = Float.valueOf(mul(currentWidth, div(list.get(i).getDuration().get(1), info.getSampleDetail().getDuration())) + "");
            Float h = Float.valueOf(mul(ivContent.getHeight(), (list.get(i).getHeight() + list.get(i).getTop())) + "");
            RectBean rectBean = new RectBean(x, y, w, h, list.get(i).getId(), list.get(i).getBackgroundColor());
            view = new MyRectView(LabelDetailActivity.this, rectBean);
            view.setOnRectClickListener(new OnRectClickListener() {
                @Override
                public void onClick(View view, String id) {
                    for (CoordinateBean bean : list) {
                        if (bean.getId() == id) {
                            //如果是标注完成 不显示删除 否则显示删除
                            if (labelStatus == 20 || labelStatus == 30) {
                                editRemark.setEnabled(false);
                                btnBiaozhuSave.setVisibility(View.GONE);
                                editRemark.setText(bean.getRemark() != null ? bean.getRemark() : "");

                                llBiaozhuWancheng.setVisibility(View.GONE);
                                llRemark.setVisibility(View.VISIBLE);
                                tvBiaozhuType.setText("框选标注");
                                initTreeView("SAMPLE_MARK_OPTION", bean);
                                drawer.openDrawer(Gravity.RIGHT);
                            } else { //显示弹窗 删除/ 查看
                                showBiaozhu(bean);
                            }
                            break;
                        }
                    }
                }
            });
            frameRect.addView(view);
        }
    }

    /**
     * 标注框
     *
     * @param bean
     */
    private void showBiaozhu(final CoordinateBean bean) {
        AlertDialog.Builder builder = new AlertDialog.Builder(LabelDetailActivity.this);
        View dialogView = LayoutInflater.from(LabelDetailActivity.this).inflate(R.layout.dialog_biaozhu, null);
        builder.setView(dialogView);
        biaozhuDialog = builder.create();
        biaozhuDialog.setCanceledOnTouchOutside(true);
        biaozhuDialog.show();

        biaozhuDialog.getWindow().setLayout(DensityUtil.dip2px(LabelDetailActivity.this, 200), LinearLayout.LayoutParams.WRAP_CONTENT);

        TextView tvDelete = dialogView.findViewById(R.id.tv_delete);
        TextView tvBiaozhu = dialogView.findViewById(R.id.tv_biaozhu);
        if (bean != null) {
            tvBiaozhu.setText("查看");
        } else {
            tvBiaozhu.setText("标注");
        }

        tvBiaozhu.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if (bean != null) {
                    editRemark.setEnabled(false);
                    btnBiaozhuSave.setVisibility(View.GONE);
                    editRemark.setText(bean.getRemark() != null ? bean.getRemark() : "");

                    llBiaozhuWancheng.setVisibility(View.GONE);
                    llRemark.setVisibility(View.VISIBLE);
                    tvBiaozhuType.setText("框选标注");
                    initTreeView("SAMPLE_MARK_OPTION", bean);
                    drawer.openDrawer(Gravity.RIGHT);
                } else {
                    editRemark.setText("");
                    drawType = 1;
                    editRemark.setEnabled(true);
                    btnBiaozhuSave.setVisibility(View.VISIBLE);

                    llBiaozhuWancheng.setVisibility(View.GONE);
                    llRemark.setVisibility(View.VISIBLE);
                    tvBiaozhuType.setText("框选标注");
                    initTreeView("SAMPLE_MARK_OPTION", null);
                    drawer.openDrawer(Gravity.RIGHT);

                }
                biaozhuDialog.dismiss();
            }
        });
        tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bean != null) {
                    //请求接口删除 标注
                    String coordinate = markDetailBean.getCoordinate();
                    List<CoordinateBean> coorlist = new ArrayList<>();
                    if (!TextUtils.isEmpty(coordinate)) {
                        List<CoordinateBean> list = GsonUtil.parseJson(coordinate, new TypeToken<List<CoordinateBean>>() {
                        });
                        coorlist.addAll(list);
                    }

                    for (int i = 0; i < coorlist.size(); i++) {
                        if (coorlist.get(i).getId().equals(bean.getId())) {
                            coorlist.remove(i);
                            break;
                        }
                    }
                    markReq.setId(markDetailBean.getId());
                    markReq.setCoordinate(GsonUtil.toJsonStr(coorlist));
                    presenter.updataMark(labelId, sampleId, markDetailBean.getId(), markReq);

                } else {
                    imageMark.deleteMark();
                }
                biaozhuDialog.dismiss();
            }
        });
    }

    /**
     * 获取sp图表数据
     *
     * @param bean
     */
    @Override
    public void downloadFileSuc(SPBean bean) {
        this.spBean = bean;
        //绘制sp
        drawSpView();
    }

    /**
     * 框选
     *
     * @param list
     */
    @Override
    public void getDictionaryListSuc1(List<ProblemBean> list) {
        if (list.size() > 0) {
            labelList.clear();
            getTreelist1(list);
        }
    }

    /**
     * 完成
     *
     * @param list
     */
    @Override
    public void getDictionaryListSuc2(List<ProblemBean> list) {
        if (list.size() > 0) {
            finishList.clear();
            getTreelist2(list);
        }
    }

    @Override
    public void updataMarkSuc() {
        tvKuangxuan.setText("框选标注");
        drawer.closeDrawer(Gravity.RIGHT);
        imageMark.deleteMark2();
    }

    @Override
    public void updataMarksSuc() {
        finish();
        EventBus.getDefault().post(new WorkYbEvent());
        showToast("标注完成");
    }


    public static void getTreelist1(List<ProblemBean> list) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getGroupCode().equals("SAMPLE_MARK_OPTION")) {
                labelList.add(new TypeBeanString(list.get(i).getId(), list.get(i).getParentId(), list.get(i).getTitle(), list.get(i).getType() + ""));
            }
            if (list.get(i).getChildren() != null && list.get(i).getChildren().size() > 0) {
                getTreelist1(list.get(i).getChildren());
            }
        }
    }

    public static void getTreelist2(List<ProblemBean> list) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getGroupCode().equals("SAMPLE_MARK_RESULT")) {
                finishList.add(new TypeBeanString(list.get(i).getId(), list.get(i).getParentId(), list.get(i).getTitle(), list.get(i).getType() + ""));
            }
            if (list.get(i).getChildren() != null && list.get(i).getChildren().size() > 0) {
                getTreelist2(list.get(i).getChildren());
            }
        }
    }

    /**
     * 绘制SP图标
     */
    private void drawSpView() {
        if (spBean == null) {
            return;
        }
        List<List<Integer>> list = LabelUtils.groupList(spBean.getData().get(0));
        int height = llContent.getHeight() - DensityUtil.dip2px(mContext, 20);
        llSp.removeAllViews();
        for (int i = 0; i < list.size(); i++) {
            SPlineView visitView = new SPlineView(LabelDetailActivity.this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            visitView.setDate(spBean.getLength(), spBean.getMaxVal(), list.get(i), xMultiple, yMultiple, height);
            visitView.setLayoutParams(params);
            llSp.addView(visitView);
        }
    }

    /**
     * 绘画分区
     */
    private void drawSection() {
        if (markDetailBean == null || sectionList.size() != 5) {
            return;
        }
        int widths = (int) (Constant.width * Math.pow(2, xMultiple));
        SampleDetailBean sampleDetail = info.getSampleDetail();
        Integer duration = sampleDetail.getDuration();// 总时长
        Log.e("TAG", "drawSection: 总长度" + widths);
        llSection.removeAllViews();
        double margin = 0;
        for (int i = 0; i < sectionList.size(); i++) {
            double width_b = BigDecimalUtil.div(sectionList.get(i)[0], duration) * widths;
            double width_e = BigDecimalUtil.div(sectionList.get(i)[1], duration) * widths;
            Log.e("TAG", "drawSection: " + width_b + "  " + width_e + "  " + (width_e - width_b));
            TextView tvSection = new TextView(this);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams((int) (width_e - width_b), DensityUtil.dip2px(this, 20));
            layoutParams.leftMargin = (int) (width_b - margin);
            tvSection.setText(i == 0 ? "第一听诊区" : i == 1 ? "第二听诊区" : i == 2 ? "第三听诊区" : i == 3 ? "第四听诊区" : i == 4 ? "第五听诊区" : "");
            tvSection.setGravity(Gravity.CENTER);
            tvSection.setTextSize(12);
            tvSection.setTextColor(getResources().getColor(R.color.white));
            tvSection.setBackgroundColor(getResources().getColor(R.color.black));
            tvSection.setLayoutParams(layoutParams);
            llSection.addView(tvSection);
            margin = width_e;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.stop();
        }
    }
}
